<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/24
 * Time: 20:14
 */

namespace Admin\Controller;


use Admin\Logic\RaceLogic;
use Admin\Model\Page;

class RaceController extends BaseController
{
    public function __construct($baseModel)
    {
        parent::__construct(D('Race'));
        $this->bcItemPush('赛事列表', U('Race/index'));
    }

    private static $_validate = array(
        array('title', 'require', '赛事标题不能为空！', 1, 'regex', 3),
        array('description', 'require', '赛事说明不能为空！', 1, 'regex', 3),
        array('region', 'require', '所属战区不能为空！', 1, 'regex', 3),
        array('systems_name', 'require', '所属系统不能为空！', 1, 'regex', 3),
        array('model', 'require', '比赛模式不能为空！', 1, 'regex', 3),
        array('integral', 'require', '所需钻石不能为空！', 1, 'regex', 3),
        array('reward_integral', 'require', '奖励钻石不能为空！', 1, 'regex', 3),
        array('people_number', 'require', '人数限制不能为空！', 1, 'regex', 3),
        array('apply_start_time', 'require', '报名开始时间不能为空！', 1, 'regex', 3),
        array('apply_end_time', 'require', '报名结束时间不能为空！', 1, 'regex', 3),
        array('game_start_time', 'require', '比赛开始时间不能为空！', 1, 'regex', 3),
        array('qr_code', 'require', '赛事群二维码不能为空！', 1, 'regex', 3),
    );

    public function index(){
        $raceModel = D('Race');
        //构建查询条件
        $pagesize = 20;
        $user_id = I('user_id');
        $region = I('region');
        $systems_name = I('systems_name');
        $model = I('model');
        $status = I('status');
        $id = I('id');
        $pagenumber = I('pagenum', '');
        if (empty($pagenumber) || $pagenumber <= 0)
            $pagenumber = 1;
        if ($user_id != '') {
            $map['t_race.user_id'] = $user_id;
        }
        if ($id != '') {
            $map['t_race.id'] = $id;
        }
        if ($region != '' && $region != '-1') {
            $map['t_race.region'] = $region;
        }
        if ($systems_name != '' && $systems_name != '-1') {
            $map['t_race.systems_name'] = $systems_name;
        }
        if ($model != '' && $model != '-1') {
            $map['t_race.model'] = $model;
        }
        if ($status != '' && $status != '-1') {
            $map['t_race.status'] = $status;
        }
        //查询
        $startno = ($pagenumber - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $map['is_delete'] = 0;
        $list = $raceModel->where($map)->order('id desc')->limit($limit)
            ->field('t_race.*')->select();
        $logic = new RaceLogic();
        $logic->updateSatus($list);//更新状态
        $recordcount = $raceModel->where($map)->count();
        //封装分页对象
        $page = new Page($pagenumber, $recordcount, $pagesize);
        $page = (array)$page;//转换为数组
        //显示数据
        $this->assign('page', $page);
        $this->assign('user_id', $user_id);
        $this->assign('id', $id);
        $this->assign('region', $region);
        $this->assign('systems_name', $systems_name);
        $this->assign('model', $model);
        $this->assign('status', $status);
        $this->assign('pagenumber', $pagenumber);
        $this->assign('list', $list);
        $this->assign('recordcount', $recordcount);
        $this->display();
    }

    public function addUI()
    {
        $this->bcItemPush('添加赛事', U('Race/addUI'));
        $this->display('save');
    }


    public function add()
    {
        $data = $this->baseModel->validate(self::$_validate)->create($_POST);
        if (!$data)
            $this->retJson(false, $this->baseModel->getError());
        $data['apply_start_time'] = strtotime($data['apply_start_time']);
        $data['apply_end_time'] = strtotime($data['apply_end_time']);
        $data['game_start_time'] = strtotime($data['game_start_time']);
        $this->checkTime($data);
        $data['is_show'] = 1;
        $data['create_time'] = time();
        $logic = new RaceLogic();
        $data['status'] = $logic->getStatus($data);
        D('Race')->add($data);
        $this->retJson(true, '添加成功！');
    }

    //判断时间
    private function checkTime($data){
        if($data['apply_start_time'] > $data['apply_end_time']){
            $this->retJson(false, '报名开始时间必须小于报名结束时间！');
        }
        if($data['apply_start_time'] > $data['game_start_time'] || $data['apply_end_time'] > $data['game_start_time']){
            $this->retJson(false, '赛事开始时间必须大于报名时间！');
        }
    }

    public function editUI($id)
    {
        $where['id'] = ':id';
        $race = $this->baseModel->where($where)->bind($where['id'], $id)->find();
        $race['description'] = html_entity_decode($race['description']);
        $race['apply_start_time'] = date('Y-m-d H:i',$race['apply_start_time']);
        $race['apply_end_time'] = date('Y-m-d H:i',$race['apply_end_time']);
        $race['game_start_time'] = date('Y-m-d H:i',$race['game_start_time']);
        $this->bcItemPush('编辑赛事', U('Race/editUI/'.$id));
        $this->assign('race', $race);
        $this->display('save');
    }

//    public function doAddAfter($data, $success){
//        $map['create_time'] = time();
//        if($success)
//        {
//            $map['id'] = $success;
//            D('Race')->save($map);
//        }
//    }

    /**
     * 报名列表
     */
    public function apply(){
        $model = M('ApplyLog');
        $pagesize = 20;
        $race_id = I('race_id');
        $user_id = I('user_id');
        $pagenumber = I('pagenum', '');
        if (empty($pagenumber) || $pagenumber <= 0)
            $pagenumber = 1;
        if(!empty($user_id)){
            $map['t_apply_log.user_id'] = $user_id;
        }
        $startno = ($pagenumber - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $map['t_apply_log.race_id'] = $race_id;
        $list = $model->join('LEFT JOIN t_user u ON u.id=t_apply_log.user_id')
            ->join('LEFT JOIN t_race r ON r.id=t_apply_log.race_id')
            ->where($map)->order('id desc')->limit($limit)
            ->field('t_apply_log.*,r.title,u.nickname,u.wechat_number,u.game_name')->select();
        foreach ($list as $key => $value) {
            $list[$key]['create_time'] = date("Y-m-d H:i:s", $list[$key]['create_time']);
        }
        $recordcount = $model->where($map)->count();
        //封装分页对象
        $page = new Page($pagenumber, $recordcount, $pagesize);
        $page = (array)$page;//转换为数组

        $status = D('Race')->where(array('id'=>$race_id))->getField('status');

        $this->bcItemPush('报名列表', U("Race/apply?race_id=$race_id"));

        $this->assign('race_id', $race_id);
        $this->assign('user_id', $user_id);
        $this->assign('pagenumber', $pagenumber);
        $this->assign('page', $page);
        $this->assign('list', $list);
        $this->assign('status', $status);
        $this->assign('recordcount', $recordcount);
        $this->display();
    }

    public function edit()
    {
        $data = $this->baseModel->validate(self::$_validate)->create($_POST);
        if (!$data)
            $this->retJson(false, $this->baseModel->getError());
        $data['apply_start_time'] = strtotime($data['apply_start_time']);
        $data['apply_end_time'] = strtotime($data['apply_end_time']);
        $data['game_start_time'] = strtotime($data['game_start_time']);
        $this->checkTime($data);
        $logic = new RaceLogic();
        $data['status'] = $logic->getStatus($data);
        D('Race')->save($data);
        $this->retJson(true, '修改成功！');
    }

    public function doDeleteBefore($id)
    {
    }

    public function delete($id)
    {
        $race = D('Race')->where(array('id'=>$id))->find();
        if(empty($race['id']) || $race['is_delete'] == 1){
            $this->ajaxReturn(array('success'=>false,'message'=>'该赛事不能删除！'));
        }
        D('Race')->where(array('id'=>$id))->setField('is_show',0);//下架
        D('Race')->where(array('id'=>$id))->setField('is_delete',1);
        $count = D('Race')->where(array('is_delete'=>1))->count();
        $this->ajaxReturn(array('success'=>true,'message'=>'删除成功！','count'=>$count));
    }

    public function updateField()
    {
        $id = I('id');
        $value = I('value');
        $field = I('field');
        $where['id'] = ':id';
        $bind[':id'] = $id;
        $category = D('Race')->where($where)->bind($bind)->find();
        $category[$field] = $value;
        $result = D('Race')->where($where)->bind($bind)->setField($field,$value);
        if($result){
            $this->ajaxReturn(array('success'=>true,'message'=>'修改成功'));
        }else{
            $this->ajaxReturn(array('success'=>false,'message'=>'修改失败'));
        }
    }

    /**
     *跳转到判定赛事界面
     */
    public function judgeUI(){
        $user_id = I('user_id');
        $race_id = I('race_id');
        $user = D('User')->where(array('id'=>$user_id))->find();
        $race = D('Race')->where(array('id'=>$race_id))->find();

        $this->bcItemPush('判定胜利者', U("Race/judgeUI?user_id=$user_id&race_id=$race_id"));

        $this->assign('user',$user);
        $this->assign('race',$race);
        $this->display('judge');
    }

    /**
     * ajax判定赛事胜利者
     */
    public function judge(){
        $user_id = I('user_id');
        $race_id = I('race_id');
        $result = $_POST['result'];
        if(empty($user_id) || empty($race_id)){
            $this->ajaxReturn(array('success'=>false,'message'=>'请勿非法提交！'));
        }
        if(empty($result)){
            $this->ajaxReturn(array('success'=>false,'message'=>'请填写赛事结果！'));
        }
        $logic = new RaceLogic();
        $success = false;
//        0失败 1成功 2该用户没有报名该赛事 3该赛事不能判定
        $status = $logic->judge($user_id,$race_id,$result);
        switch($status){
            case 0:
                $message = '判定失败！';
                break;
            case 1:
                $success = 1;
                $message = '判定成功，已保存结果！';
                break;
            case 2:
                $message = '对不起，该用户没有报名该赛事';
                break;
            case 3:
                $message = '对不起，该赛事不正在进行中！';
                break;
        }
        $this->ajaxReturn(array('success'=>$success,'message'=>$message));
    }

}